#include "ssicloud_vs_eventtrack.h"

using namespace ssicloud;
VSEventTrack::VSEventTrack()
    : ItemObject<EmptyInfoNode>(LQ_BASE_URL "/vs/eventTrack/add"
                           , OBJECT_NAME_VSEventTrack
                           , NetUrl::NET_HTTP_METHOD_POST)
{
    mUrl.appendHeader(HEADER_JSON);
    mUrl.appendHeader(HEADER_TOKEN);
    // mUrl.append("vin",        VIN_STRING);
}

bool VSEventTrack::postEventInfo(EventTrackIn &in)
{
    if (isLoading()) {
        GEN_Printf(LOG_WARN, "current is loading.");
        return false;
    }

    cJSON *root = cJSON_CreateObject();

    cJSON_AddStringToObject(root, "vin", VIN_STRING);

    cJSON *eventList = cJSON_AddArrayToObject(root, "eventList");


    cJSON *event = cJSON_CreateObject();

    cJSON_AddStringToObject(event, "eventId", in.eventId.c_str());
    cJSON_AddStringToObject(event, "eventParam", in.eventParam.c_str());
    cJSON_AddNumberToObject(event, "viewNum",   in.viewNum);
    cJSON_AddNumberToObject(event, "viewSuccessNum", in.viewSuccessNum);
    cJSON_AddStringToObject(event, "uploadTime", in.uploadTime.c_str());

    cJSON_AddItemToArray(eventList, event);

    // char *out = cJSON_PrintUnformatted(root);
    // GEN_Printf(LOG_DEBUG, "%s", out);

    cJSON_PrintPreallocated(root, m_body, sizeof (m_body)-1, false);
    // GEN_Printf(LOG_DEBUG, "%s", m_body);
    mUrl.appendBody(m_body);
    return obtain();
}

int VSEventTrack::genResult(NetBuffer *data)
{
    int ret = KL_DATA_PRISER_OK;
    GEN_Printf(LOG_DEBUG, "size: %lu\n%s", data->size(), (char *)data->buffer());
    cJSON *root = cJSON_Parse((char *)data->buffer(), data->size());
    cJSON *code = cJSON_GetObjectItem(root, "code");
    if (code && *(code->valuestring) == '1')
    {
        // cJSON_GetStringValue()
        // GEN_Printf(LOG_DEBUG, "code value = %d, %s", (int)code->valuedouble);
        GEN_Printf(LOG_INFO, "upload info successfully.");
    } else
    {
        GEN_Printf(LOG_ERROR, "priser failed, size: %lu\n%s", data->size(), data->buffer());
        ret = KL_DATA_PRISER_JSOC_ERROR;
    }

    cJSON_Delete(root);
    return ret;
}

void VSEventTrack::profile()
{

}
